<template>
  <div class="container">
    <!--控制区域-->
    <div class="controls-wrapper">
      <div class="controls border-and-shadow">
        <!--第一行,kafka控制区域-->
        <kafka-connect :send-count="sendCount" @onSend="sendAll"></kafka-connect>
        <!--第二行,普通按钮-->
        <div>
          <button @click="selectAll">全选</button>
          <button @click="selectNone">全取消</button>
          <button @click="openDevtool">开启F12</button>
        </div>
      </div>
    </div>
    <!--消息区域-->
    <div class="messages">
      <business-frame v-for="(item, idx) in allObject.businesses"
                      :businesses="item"
                      :key="idx">
      </business-frame>
    </div>
  </div>
</template>

<script>
import BusinessFrame from './BusinessFrame/index.vue'
import KafkaConnect from './KafkaConnect/index.vue'
import {ipcRenderer} from 'electron'
import {replaceTime} from '../utils/StringUtils'
import io from '../api/io.js'

export default {
  name: 'Protocol42',
  components: {KafkaConnect, BusinessFrame},
  data () {
    return {
      allObject: {},
      sendCount: 0 // 发送的所有消息的数量,由父组件提供给子组件
    }
  },
  methods: {
    async openDevtool () {
      ipcRenderer.invoke('open-devtools', null)
    },
    open (link) { // 本方法尚未使用
      this.$electron.shell.openExternal(link)
    },
    selectAll () {
      this.allObject.businesses.forEach(busi => {
        busi.messages.forEach(message => {
          message.enabled = true
        })
      })
    },
    selectNone () {
      this.allObject.businesses.forEach(busi => {
        busi.messages.forEach(message => {
          message.enabled = false
        })
      })
    },
    sendAll () {
      this.allObject.businesses.forEach(busi => {
        busi.messages.forEach(message => {
          const messageType = message.name
          const content = message.value
          // 对应checkbox没有选中的,不予发送
          if (!message.enabled) return
          // 根据messageType,获取对应的topic
          const topic = io.getTopicByMessageType(messageType)
          if (!topic) {
            console.error('没有对应的topic: ' + messageType)
            return
          }
          // 对消息进行时间处理
          const newContent = replaceTime(content)
          // 发送kafka
          ipcRenderer.invoke('sendMessageChannel', topic, newContent)
          this.sendCount++
        })
      })
    }
  },
  created () {
    this.allObject = io.readMap()
  }
}
</script>

<style scoped>

</style>
